import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, message } from 'antd';
import { UserOutlined, LogoutOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import Login from './components/Login';
import AIRecords from './components/AIRecords';
import PurchaseRecords from './components/PurchaseRecords';
import './App.css';

const { Header, Content } = Layout;

const App: React.FC = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [token, setToken] = useState('');
  const [activeTab, setActiveTab] = useState('ai');

  // 页面加载时检查localStorage中是否有token
  useEffect(() => {
    const savedToken = localStorage.getItem('token');
    if (savedToken) {
      setToken(savedToken);
      setIsLoggedIn(true);
    }
  }, []);

  const handleLogin = (newToken: string) => {
    setToken(newToken);
    setIsLoggedIn(true);
    localStorage.setItem('token', newToken);
  };

  const handleLogout = () => {
    setToken('');
    setIsLoggedIn(false);
    localStorage.removeItem('token');
    message.success('已成功登出');
  };

  const handleMenuSelect = (info: { key: string }) => {
    setActiveTab(info.key);
  };

  return (
    <Layout className="layout">
      <Header>
        <div className="logo" />
        {isLoggedIn ? (
          <>
            <Menu
              theme="dark"
              mode="horizontal"
              selectedKeys={[activeTab]}
              onSelect={handleMenuSelect}
            >
              <Menu.Item key="ai">AI记录</Menu.Item>
              <Menu.Item key="purchase">购买记录</Menu.Item>
            </Menu>
            <Button
              type="text"
              icon={<LogoutOutlined />}
              onClick={handleLogout}
              style={{ color: 'white', float: 'right' }}
            >
              登出
            </Button>
          </>
        ) : (
          <div style={{ float: 'right' }}>
            <UserOutlined style={{ color: 'white', marginRight: '8px' }} />
            <span style={{ color: 'white' }}>请登录</span>
          </div>
        )}
      </Header>
      <Content style={{ padding: '0 20px', marginTop: 10 }}>
        {!isLoggedIn ? (
          <Login onLogin={handleLogin} />
        ) : (
          <div className="site-layout-content">
            {activeTab === 'ai' ? (
              <AIRecords token={token} />
            ) : (
              <PurchaseRecords token={token} />
            )}
          </div>
        )}
      </Content>
    </Layout>
  );
};

export default App; 